package org.cos.verification.verifier;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.midlet.MIDlet;

import org.cos.verification.automata.Automata;
import org.cos.verification.automata.AutomataParser;
import org.shellex.javame.utility.BackgroundTask;
import org.shellex.javame.utility.IOWrapper;
import org.shellex.javame.utility.ProgressGaugeUI;
import org.shellex.javame.utility.ProgressObserver;
import org.shellex.javame.utility.Screen;

public class CheckProgressScreen extends Screen implements ProgressObserver {
	private static final int GAUGE_MAX = 20;
	private static final int GAUGE_LEVELS = 1;
	public Form screen = null;
	private Gauge gauge = null;
	Command abort_cmd = null;
	private boolean stoppable;
	private boolean stopped;
	int current;
	Display display = null;

	static CheckProgressScreen instance;

	public static CheckProgressScreen getInstance() {
		if (instance == null)
			instance = new CheckProgressScreen();
		return instance;
	}

	public CheckProgressScreen() {
	}

	public void crackCommand(MIDlet midlet, Command cmd, Displayable screen) {
		if (cmd == abort_cmd) {
			if (isStoppable())
				stopped = true;
			else
				setPrompt("can't stop!");
		}
	}

	public Screen initCommand() {
		abort_cmd = new Command("中止", Command.CANCEL, 1);
		screen.addCommand(abort_cmd);
		return this;
	}

	public Screen initUI(MIDlet midlet) {
		screen = new Form("CoS 模型校验器正在工作...");
		gauge = new Gauge("", false, GAUGE_MAX, 0);
		gauge.setPreferredSize(1000, 200);
		screen.append(gauge);
		display = Display.getDisplay(midlet);
		return this;
	}

	public void setCommandListener(CommandListener cmdl) {
		screen.setCommandListener(cmdl);

	}

	public void display(MIDlet midlet) {
		ProgressObserver poUI = ProgressGaugeUI.getInstance();
		BackgroundTask bkTask = new BackgroundTask(this, screen, display) {
			public void runTask() {
				alertScreen = new Alert(
						"user cancel",
						"you press the cancel button and the screen will jump to the main Form",
						null, AlertType.ERROR);
				alertScreen.setTimeout(Alert.FOREVER);
				needAlert = true;
				
				String app_name = SharePool.getInstance().crr_filename;
				String app_path = SharePool.getInstance().crr_filepath;
				AutomataParser ap = new AutomataParser();
				String model_xml = IOWrapper.getInstance()
						.read_file(SharePool.getInstance().crr_filename);
				ap.parse(model_xml);
				Automata model = ap.get_automata();
				System.out.println("Parse OK");
				int i = 0;
				for (; i < 1; i += 1) {
					getProgressObserver().updateProgress(
							"Progress: " + i + "/" + 20);
					if (getProgressObserver().isStopped()) {
						System.out.println("Canceled");
						return;
					}
					String policy_xml= IOWrapper.getInstance().read_res_UTF("/policy_def.xml");
					ap.parse(policy_xml);
					Automata policy = ap.get_automata();

					Automata result = model.merge(policy);
					//model.print();
					//policy.print();
					result.print();
					if (result.check()) {
						System.out
								.println("[Warning] Model conflicts with the policy "
										+ i);
						CheckReportScreen.getInstance().add_result("[Conflict] Policy "+ i, "Unknow");
					} else {
						System.out
								.println("[Warning] Model adapts to the policy "
										+ i);
					}
					
				}
				getProgressObserver().setMax();
				CheckReportScreen.getInstance().set_summary(i + "/" + 10);
				CheckReportScreen.getInstance().set_app(app_name, app_path);
				
				display.setCurrent(CheckReportScreen.getInstance().screen);
				taskComplete();
			}
		};
		BackgroundTask.runWithProgressGauge(bkTask, "CoS 模型校验器正在工作...",
				"Prepera...", true, display);
	}

	public void exit() {
		// TODO Auto-generated method stub

	}

	public boolean isStoppable() {
		return stoppable;

	}

	public boolean isStopped() {
		return stopped;
	}

	public void reset() {
		// TODO Auto-generated method stub

	}

	public void setMax() {
		// TODO Auto-generated method stub

	}

	public void setTitle(String title) {
		screen.setTitle(title);
	}

	public void setPrompt(String prompt) {
		gauge.setLabel(prompt);
	}

	public void setStoppable(boolean stoppable) {
		this.stoppable = stoppable;
		if (stoppable) {
			screen.addCommand(abort_cmd);
		} else {
			screen.removeCommand(abort_cmd);
		}
	}

	public void setStopped(boolean stopped) {
		// TODO Auto-generated method stub

	}

	public void show(Display display) {
		display.setCurrent(screen);
	}

	public void updateProgress(Object param1) {
		System.out.println(current);
		current = (current + 1) ;//% GAUGE_LEVELS;
		gauge.setValue(current );//* GAUGE_MAX / GAUGE_LEVELS);
		if (param1 != null && param1 instanceof String) {
			setPrompt((String) param1);
		}
	}
}
